<?php
// +----------------------------------------------------------------------
// | User: zq
// +----------------------------------------------------------------------
// | Time: 2021/12/13 13:25
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Wx;

use App\Exceptions\BusinessException;
use App\Inputs\PageInput;
use App\Models\Goods\Goods;
use App\Models\Promotion\GrouponRules;
use App\Services\Goods\GoodsService;
use App\Services\Promotion\GrouponService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

class GrouponController extends WxController
{
    /**
     * @return JsonResponse
     * @throws BusinessException
     */
    public function list()
    {
        $page = PageInput::new();
        $list = GrouponService::getInstance()->getGrouponRules($page);

        $rules = collect($list->items());
        $goodsIds = $rules->pluck('goods_id')->toArray();
        $goodsList = GoodsService::getInstance()->getGoodsListByIds($goodsIds)->keyBy('id');

        $voList = $rules->map(function (GrouponRules $grouponRules) use ($goodsList) {
            /** @var Goods $goods */
            $goods = $goodsList->get($grouponRules->goods_id);
            return [
                'id' => $goods->id,
                'name' => $goods->name,
                'brief' => $goods->brief,
                'picUrl' => $goods->pic_url,
                'counterPrice' => $goods->counter_price,
                'retailPrice' => $goods->counter_price,
                'grouponPrice' => bcsub($goods->retail_price, $grouponRules->discount, 2),
                'groupDiscount' => $grouponRules->discount,
                'groupMember' => $grouponRules->discount_member,
                'expireTime' => $grouponRules->expire_time
            ];
        });

        $list = $this->paginate($list, $voList);
        return $this->success($list);
    }

    protected $except = ['test'];

    public function test()
    {
        $rules = GrouponService::getInstance()->getGrouponRulesById(1);
        $resp = GrouponService::getInstance()->createGrouponShareImage($rules);

        $directory = resource_path('image');
        $files = Storage::files($directory);
        dd($files);


        return $resp;
        // return response()->make($resp)->header('Content-Type', 'image/png');
    }
}